package service;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import entity.MasterConfig;
import utils.Base;
import utils.TcpSocketUtil;

public class DSTConsoleService {
    public int shutdownServer()
    {
        return TcpSocketUtil.connect("c_shutdown(true)\n");
    }

    public int announce(String message)
    {
        String cmd = "c_announce(\"" + message +  "\")\n";
        return TcpSocketUtil.connect(cmd);
    }

    /**
     * 踢出玩家
     * @param userId klei的userId
     */
    public int kickPlayer(String userId) {
        String cmd = "TheNet:Kick(" + userId + ")\n";
        return TcpSocketUtil.connect(cmd);
    }


    /**
     * 回滚指定的天数
     * @param dayNum 1-5天
     */
    public int rollback(int dayNum){
        String CMD = "c_rollback(" + dayNum + ")\n";
        return TcpSocketUtil.connect(CMD);
    }


    /**
     * 重置世界
     */
    public int regenerate(){
        String CMD = "c_regenerateworld()\n";
        return TcpSocketUtil.connect(CMD);
    }


    /**
     * 解析日志获取玩家信息
     * [14:18:00]: playerlist 1621253438444 [0] KU_c1gvcIl4 [Host]
     * [14:18:00]: playerlist 1621253438444 [1] KU_***** nickname wendy
     * @return ku_** 昵称 角色
     */
    public int getPlayerList(Path logPath, List<String> playList){
        String playerPrefix = "KU_";
        String host = "[Host]";
        String timeMillis = System.currentTimeMillis()+"";
        String MASTER_PLAYLIST_CMD = "for i, v in ipairs(TheNet:GetClientTable()) do  print(string.format(\"playerlist %s [%d] %s %s %s\", 99999999, i-1, v.userid, v.name, v.prefab )) end\n";
        String cmd = MASTER_PLAYLIST_CMD.replace("99999999",timeMillis);
        // String cmd = MASTER_PLAYLIST_CMD;
        int res = TcpSocketUtil.connect(cmd);
        if (res != 0) return res;

        try {
            Thread.sleep(1000);
        } catch (Exception e) {
            e.printStackTrace();
        }

        List<String> dstLog = Base.readLastNLines(logPath.toAbsolutePath().toString(), 100);
        System.out.println("[debug] dstLog in: " + logPath.toAbsolutePath().toString());
        System.out.println("[debug] dstLog last 100 lines: " + dstLog);
        if (!dstLog.isEmpty()){
            dstLog.forEach(e->{
                if (e.contains(timeMillis)){
                    if (e.contains(playerPrefix)){
                        String tmp = e.substring(e.indexOf(playerPrefix));
                        if (!tmp.contains(host)){
                            playList.add(tmp);
                        }
                    }
                }
            });
            return 0;
        }
        
        return 1;
    }

}
